'use strict';

const fs = require('fs')

const addMapping = (router, mapping) => {
    for (var url in mapping) {
        var path = ''
        if (url.startsWith('GET ')) {
            path = url.substring(4)
            router.get(path, mapping[url]);
            console.log(`register URL mapping : GET ${path}`)
        } else if (url.startsWith('POST ')){
            path = url.substring(5)
            router.post(path, mapping[url]);
            console.log(`register URL mapping : POST ${path}`);
        } else {
            console.log(`invalid URL: ${url}`);
        }
    }
}

const addControllers = (router, dir) => {
    let files = fs.readdirSync(__dirname + '/' + dir);
    var js_files = files.filter(f => {
        return f.endsWith('.js')
    })
    for (var f of js_files) {
        console.log(`process controller: ${f}`)
        let mapping = require(__dirname + '/controllers/' + f)
        addMapping(router, mapping)
    }
}

module.exports = (dir = 'controllers') => {
    let router = require('koa-router')();
    addControllers(router, dir);
    return router.routes();
}